package com.tanhua.manager.service;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.Admin;
import com.tanhua.dubbo.api.db.AdminApi;
import com.tanhua.manager.exceptions.TanhuaException;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.tanhua.commons.utils.JwtUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class AdminService {

    @Autowired
    private StringRedisTemplate redisTemplate;
 
//  存储验证码的前缀
    private static final String CACHE_KEY_CAP_PREFIX = "MANAGE_CAP_";

    @DubboReference
    private AdminApi adminApi;

    //根据登录token，获取用户对象
 //根据登录token，获取用户对象
    public Admin findAdminByToken(String token) {
        Claims claims = JwtUtils.getClaims(token);
        Long id = claims.get("id", Long.class);
        String username = claims.get("username", String.class);
        Admin admin = new Admin();
        admin.setId(id);
        admin.setUsername(username);
        return admin;
    }

    public ResponseEntity verification(String uuid, HttpServletResponse response) throws Exception {
//        生成一个验证码图片，返回到浏览器
//        CAPTCHA
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 100);
        String captchaCode = lineCaptcha.getCode();
//        生成验证码 把内容存到redis
        redisTemplate.boundValueOps(CACHE_KEY_CAP_PREFIX+uuid).set(captchaCode,5, TimeUnit.MINUTES);
        ServletOutputStream outputStream = response.getOutputStream();
        lineCaptcha.write(outputStream);
        return ResponseEntity.ok(null);


    }

    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {

//        判断用户名和密码是否为空  但凡有一个为空就不行
        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            throw new TanhuaException(500,"用户名或密码不能为空");
        }
//        先从redis中获取验证码，
        String captchaCode = redisTemplate.boundValueOps(CACHE_KEY_CAP_PREFIX + uuid).get();
//         有可能获取不到，抛异常的方式告诉前端
        if(StringUtils.isBlank(captchaCode)){
            throw new TanhuaException(500,"验证码已超时，请重新生成");
        }
//         有可能获取到，比较两个验证码
        if(!StringUtils.equals(captchaCode,verificationCode)){
//            两个验证码有可能不一样 抛异常的方式告诉前端
            throw new TanhuaException(500,"验证码错误");
        }
//         根据用户名查询表中的数据  select * from tb_admin where  username=??
        Admin admin = adminApi.findByUsername(username);
//          如果根据用户名查不到用户了 用户名错误 抛异常的方式告诉前端
        if(admin==null){
            throw new TanhuaException(500,"用户名错误");
        }
//          如果根据用户名查到用户了 再比较密码
        String passwordDb = admin.getPassword();
        String passwordPage = DigestUtils.md5Hex(password);
        //明文的密码要加密成密文的密码
        if(!StringUtils.equals(passwordDb,passwordPage)){
//            两个密码有可能不一样 抛异常的方式告诉前端
            throw new TanhuaException(500,"密码错误");
        }

        Map map = new HashMap();
        map.put("id",admin.getId());
        map.put("username",admin.getUsername());
        String token = JwtUtils.createToken(map);

        Map resultMap = new HashMap();
        resultMap.put("token",token);

        return ResponseEntity.ok(resultMap);


    }
}